import BaseView from "../view/BaseView.vue"
import Login from "../view/login/Login.vue";
import {createRouter, createWebHashHistory} from "vue-router";
import {ElMessage} from "element-plus";
import Home from "../view/Home/Home.vue";
import request from "../axios/index.js";
import Exma from "../view/Exma/Exma.vue";
import ExmaList from "../view/Exma/List.vue";

const routes = [
    {
        path: '/login',
        name: 'login',
        component: Login
    },
    {
        path: '/',
        name: 'base',
        component: BaseView,
        children: [
            {
                path: '/home',
                name: 'home',
                component: Home
            },
            {
                path: '/exma',
                name: 'exma',
                component: Exma
            },
            {
                path: '/exmalist',
                name: 'exmaList',
                component: ExmaList
            }
        ]
    },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes,
})

// 路由守卫 未登录强制跳转 login 页面
router.beforeEach((to, from, next) => {
    if (to.name !== 'login'){
        request.get('/user/user').then(res => {
            if (res.code !== 0){
                ElMessage.warning("请先登录")
                localStorage.setItem("token","")
            }else {
               localStorage.setItem("token",JSON.stringify(res.data))
            }
        })
        let token = localStorage.getItem('token')
        if (token) {
            if (to.name === 'base'){
                next({ name: 'home' })
            }
            next()
        } else {
            next({ name: 'login' })
        }
    }else {
        next();
    }
})

export default router;
